package example.questionText;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.coderside.core.ParseCore;
import com.coderside.core.base.Matcher;
import com.coderside.core.base.State;
import com.coderside.core.base.Term;

/**
*auto create by Build Tool
**/
public class QuestionBeanParse<T> extends ParseCore<T> {
	public QuestionBeanParse(InputStream in, Class<T> clazz, Class<? extends State> classz) {
		super(in, clazz, classz);
	}

	public QuestionBeanParse(String content, Class<T> clazz, Class<? extends State> classz) {
		super(new ByteArrayInputStream(content.getBytes()), clazz, classz);
	}

	public void parseLine(String line, List<Term> list) {
		if (StringUtils.isEmpty(line)) {
			return;
		}
		Class[] classes = QuestionBeanHelper.classes;
		for (Class clazz : classes) {
			try {
				Matcher inter = (Matcher) clazz.newInstance();
				if (inter.match(line)) {
					Term t = new Term();
					Object content = inter.fetch(line);
					t.setContent(content.toString());
					t.setType(inter.getType());
					list.add(t);
				}
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 当列表为空插入一个开始标志
	 * 或者当列表中最后一个元素是结束标志也插入一个开始标志
	 */
	protected boolean doBegin(List<Term> list) {
		if (list.size() == 0) {
			Term t = new Term();
			t.setType(State.BEGIN);
			list.add(t);
		} else {
			Term term = list.get(list.size() - 1);
			if (term.getType() == State.END) {
				Term t = new Term();
				t.setType(State.BEGIN);
				list.add(t);
			}
		}

		return false;
	}

	protected boolean doEnd(List<Term> list) {
		if (list.size() == 0)
			return false;
		Term term = list.get(list.size() - 1);
		if (QuestionBeanHelper.ITEMS == term.getType()) {
			Term t = new Term();
			t.setType(State.END);
			list.add(t);
		}
		return false;
	}
}
